'use server';

import View from './view';
import { notFound, forbidden, redirect } from 'next/navigation';
import { BoardLayout } from '@/constants/forum';
import { checkAuthServer } from '@/lib/api/auth';
import { fetchBoard } from '@/lib/api/forum/board';
import { fetchPostData } from '@/lib/api/forum/post';
import { checkPermission } from '@/lib/utils/server';
import PermissionDenied from '@/app/(main)/(forum)/board/_component/PermissionDenied';

export default async function PostView({ params }: { params: Promise<{ id: string }> })
{
	const { id } = await params;

	if (!/^\d+$/.test(id)) {
		return forbidden();
	}

	// 게시글 정보 조회
	const post = await fetchPostData(Number(id));

	if (!post.success || !post.data) {
		return notFound();
	}

	// 게시판 조회
	const board = await fetchBoard(post.data.boardCode);

	if (!board || !board.data) {
		return notFound();
	}

	if (!board.data.isActive) {
		return forbidden();
	}

	if (!board.data.boardMeta) {
		throw new Error('게시판 속성을 찾을 수 없습니다.');
	}

	// 1:1 게시판은 로그인한 사용자만 접근 가능
	if (board.data.boardMeta.list.layout === BoardLayout.QnA && !await checkAuthServer()) {
		redirect('/login');
	}

	// 게시판 접근 권한 확인
	if (!await checkPermission(board.data.boardMeta.permission.boardAccess, board.data.boardManager)) {
		return <PermissionDenied _board={board.data} />;
	}

	// 게시글 열람 권한 확인
	if (!await checkPermission(board.data.boardMeta.permission.postView, board.data.boardManager)) {
		return <PermissionDenied _board={board.data} />;
	}

    return (
		<View _board={board.data} _post={post.data} />
	);
}